package com.vote.thrift.service;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.commons.lang.math.NumberUtils;
import org.apache.log4j.Logger;

import org.apache.thrift.TProcessor;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TBinaryProtocol.Factory;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TServerTransport;
import org.apache.thrift.transport.TTransportException;

import com.vote.thrift.utils.CommentUtils;
import com.vote.thrift.utils.impl.CommentUtilsImpl;

public class Run {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(Run.class);

    public static final String confFile = "/conf.properties";
	
	public static void main(String[] args) {
		try {
			InputStream inputStream = null;
			
			inputStream = Object.class.getResourceAsStream(confFile);
			if(inputStream == null){
				logger.info("get configure file from FileInputStream");
				try {
					inputStream = new FileInputStream("conf/conf.properties");
				} catch (FileNotFoundException e1) {
					logger.error("get configure file from FileInputStream fail~~", e1);
				}
			}else{
				logger.info("get configure file from class.getResourceAsStream");
			}
			Properties p = new Properties();
			try {
				p.load(inputStream);
			} catch (IOException e) {
				logger.error("properties load conf.properties fail !!", e);
				return;
			}
			
			logger.info("\ncassandra.host = " + p.getProperty("cassandra.host") +
						"\ncassandra.port = " + p.getProperty("cassandra.port") + 
						"\ncassandra.keySpace = " + p.getProperty("cassandra.keySpace") + 
						"\nservice.port = " + p.getProperty("service.port"));
			
			CommentUtilsImpl commentUtils = new CommentUtilsImpl();
			if(!commentUtils.init(p.getProperty("cassandra.host"), p.getProperty("cassandra.port"), p.getProperty("cassandra.keySpace"))){
				logger.error("init CommentUtils fail!!");
				return;
			}
			TProcessor processor = new CommentUtils.Processor(commentUtils);
			TServerTransport transport = new TServerSocket(NumberUtils.toInt(p.getProperty("service.port")));
			Factory protFactory = new TBinaryProtocol.Factory(true, true);
			TServer server = new TThreadPoolServer(processor, transport, protFactory);
			System.out.println("service startup~");
			server.serve();
		} catch (TTransportException e) {
			logger.error("create transport fail", e);
		}
	}
}
